import tkinter as tk
from tkinter import ttk, filedialog, messagebox
import subprocess
import threading
import time
import pandas as pd
from datetime import datetime
import os


class PingApp:
    def __init__(self, root):
        self.root = root
        self.root.title("Ping Monitor")

        self.ip_list = []
        self.ping_threads = []
        self.interval = 5  # 默认ping周期
        self.log_dir = ""

        self.create_widgets()

    def create_widgets(self):
        # 创建IP输入框和添加按钮
        self.ip_entry_var = tk.StringVar()
        self.ip_entry = ttk.Entry(self.root, textvariable=self.ip_entry_var, width=20)
        self.ip_entry.pack(pady=5)

        self.add_ip_button = ttk.Button(self.root, text="添加IP", command=self.add_ip)
        self.add_ip_button.pack(pady=5)

        # 创建周期输入框和设置按钮
        self.interval_entry_var = tk.IntVar(value=self.interval)
        self.interval_entry = ttk.Entry(self.root, textvariable=self.interval_entry_var, width=5)
        self.interval_entry.pack(pady=5)

        self.set_interval_button = ttk.Button(self.root, text="设置周期", command=self.set_interval)
        self.set_interval_button.pack(pady=5)

        # 创建选择日志目录按钮
        self.set_log_dir_button = ttk.Button(self.root, text="选择日志目录", command=self.set_log_dir)
        self.set_log_dir_button.pack(pady=5)

        # 创建开始和停止按钮
        self.start_button = ttk.Button(self.root, text="开始Ping", command=self.start_ping)
        self.start_button.pack(pady=5)

        self.stop_button = ttk.Button(self.root, text="停止Ping", command=self.stop_ping, state=tk.DISABLED)
        self.stop_button.pack(pady=5)

        # 显示IP列表
        # self.ip_listbox = ttk.Listbox(self.root, height=10, width=30)
        self.ip_listbox = tk.Listbox(self.root, height=10, width=30)
        self.ip_listbox.pack(pady=5)

        # 填充初始IP列表
        for ip in self.ip_list:
            self.ip_listbox.insert(tk.END, ip)

    def add_ip(self):
        ip = self.ip_entry_var.get()
        if ip and ip not in self.ip_list:
            self.ip_list.append(ip)
            self.ip_listbox.insert(tk.END, ip)
            self.ip_entry_var.set("")

    def set_interval(self):
        try:
            self.interval = int(self.interval_entry_var.get())
        except ValueError:
            messagebox.showerror("输入错误", "请输入有效的整数周期")

    def set_log_dir(self):
        self.log_dir = filedialog.askdirectory()
        if self.log_dir:
            print(f"日志目录设置为: {self.log_dir}")

    def start_ping(self):
        if not self.ip_list:
            messagebox.showwarning("警告", "请先添加IP")
            return
        if not self.log_dir:
            messagebox.showwarning("警告", "请先设置日志目录")
            return

        self.stop_ping_flag = threading.Event()
        self.stop_ping_flag.clear()

        self.ping_threads = []
        for ip in self.ip_list:
            thread = threading.Thread(target=self.ping_ip, args=(ip,))
            thread.start()
            self.ping_threads.append(thread)

        self.start_button.config(state=tk.DISABLED)
        self.stop_button.config(state=tk.NORMAL)

    def stop_ping(self):
        self.stop_ping_flag.set()
        for thread in self.ping_threads:
            thread.join()

        self.start_button.config(state=tk.NORMAL)
        self.stop_button.config(state=tk.DISABLED)

    def ping_ip(self, ip):
        while not self.stop_ping_flag.is_set():
            try:
                result = subprocess.run(['ping', '-c', '1', ip], stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                                        text=True)
                success = "1 packets transmitted, 1 received" in result.stdout
                timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

                self.log_to_excel(ip, success, timestamp)

            except Exception as e:
                print(f"Ping {ip} failed: {e}")

            time.sleep(self.interval)

    def log_to_excel(self, ip, success, timestamp):
        today = datetime.now().strftime("%Y-%m-%d")
        filename = os.path.join(self.log_dir, f"ping_log_{today}.xlsx")

        if not os.path.exists(filename):
            df = pd.DataFrame(columns=["IP", "Success", "Timestamp"])
            df.to_excel(filename, index=False)

        df = pd.read_excel(filename)
        df = df.append({"IP": ip, "Success": success, "Timestamp": timestamp}, ignore_index=True)
        df.to_excel(filename, index=False)


if __name__ == "__main__":
    root = tk.Tk()
    app = PingApp(root)
    root.mainloop()